<!-- 系统升级 -->
<template>
  <div>
     <a-modal 
      v-model="update_dialog"
      :title="$t('System-update')"
      @cancel="handleCancel"
      :maskClosable="false"
      :closable="!(current==3)"
      :keyboard="false"
      v-dragModal
    >
      <a-steps :current="current" progress-dot>
        <a-step 
          v-for="item in steps" 
          :key="item.title"
          :title="$store.state.language=='zh' ? item.ch_title : item.en_title" 
          :description="$store.state.language=='zh' ? item.ch_tip : item.en_tip"
        />
      </a-steps>
      <!-- 步骤条内容 -->
      <div class="steps-content">
        <!-- 步骤一内容 -->
        <div v-show="current === 0">
          <div class="top-tip">
            <!-- <i class="icon icon-exclaim64f tip-icon"></i> -->
            <Iconfont class="icon tip-icon" type="icon-exclaim64f"></Iconfont>
            <span v-if="$store.state.language=='zh'">您即将进行系统升级，该操作需要重启整个系统的全部服务，并导致诸如磁盘检测，日志导出，磁盘创建等正在执行的进程中断，请务必保证您已知晓全部风险并已做好准备，以免造成不可挽回的损失。</span>
            <span v-else>You are about to upgrade the system. This operation requires restarting all services of the entire system, and will cause the interruption of ongoing processes such as disk detection, log export, disk creation, etc. Please ensure that you are aware of all risks and are prepared to avoid irreversible losses.</span>
          </div>
          <p v-if="$store.state.language=='zh'">如需继续操作，请在下框中输入如下文字确认操作：</p>
          <p v-else>To continue, please enter the following text in the box below to confirm the operation:</p>
          <div class="warn-tip">
            <span v-if="$store.state.language=='zh'">我已知晓全部风险，仍要升级</span>
            <span v-else>I know all the risks and still need to upgrade</span>
          </div>
          <!-- 请输入上面文字 -->
          <a-input v-model="confirmInputValue" :placeholder="$t('Enter-top-text')"></a-input>
        </div>

        <!-- 步骤二内容 -->
        <div v-show="current === 1">
          <div class="top-tip">
            <!-- <i class="icon icon-exclaim64f tip-icon"></i> -->
            <Iconfont class="icon tip-icon" type="icon-exclaim64f"></Iconfont>
            <span v-if="$store.state.language=='zh'">当前系统版本号为 PentaStor {{currentVersion}}，请导入升级安装包文件，该文件版本号必须<span class="font-weight-color">高于</span>当前系统版本号，升级安装文件请联系五舟工作人员索取。</span>
            <span v-else>The current system version number is PentaStor {{currentVersion}}. Please import the upgrade installation package file. The file version number must be<span class="font-weight-color">higher than</span> the current system version number. Please contact the staff of Wuzhou for the upgrade installation file.</span>
          </div>
          <div>
            <!-- 上传升级包 -->
            <span>{{$t('Upload-packet')}}：</span>
            <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
              <a-button :loading="uploadLoading" style="width:100px"><a-icon type="upload" />{{$t('Upload')}}</a-button>
            </a-upload>
          </div>
        </div>

        <!-- 步骤三内容 -->
        <div v-show="current === 2">
          <!-- 正在检测升级包，请稍候 -->
          <PacketOperationTip 
            :packetStatus="packetStatus"
          />
          <div class="version-div">
            <a-row v-for="(item,index) in versionTips" :key="index">
              <a-col :span="10">
                <div class="version-tip-label">{{$store.state.language=='zh' ? item.ch_title : item.en_title}}</div>
              </a-col>
              <a-col :span="14" v-if="index != 1">
                <div class="version-tip-value">{{item.value}}</div>
              </a-col>
              <a-col :span="14" v-else>
                <!-- 新版本 -->
                <!-- 低于或等于当前版本 -->
                <div
                  v-if="packetStatus == 1 || packetStatus == 2 || packetStatus == 4"
                  class="version-tip-value"
                  :class="packetStatus == 1 || packetStatus == 2 ? 'warn-color' : packetStatus == 4 ? 'ok-color' : ''"
                >
                  {{item.value=='-' ? item.value : 'PentaStor '+item.value}}
                </div>
                <!-- 错误/已损坏 -->
                <div class="version-tip-value error-color" v-else-if="packetStatus==3">{{$store.state.language=='zh' ? '错误/已损坏' : 'Error/loss'}}</div>
                <!-- <div class="version-tip-value" v-else>-</div> -->
              </a-col>
            </a-row>
          </div>
        </div>

        <!-- 步骤四 -->
        <div v-show="current === 3">
          <div class="top-tip">
            <!-- <i class="icon icon-exclaim64f tip-icon"></i> -->
            <Iconfont class="icon tip-icon" type="icon-exclaim64f"></Iconfont>
            <span v-if="$store.state.language=='zh'">系统正在升级，升级期间，所有功能将不可用。此过程将预计耗费20分钟-几小时不等，具体耗时视系统复杂度而定，升级完成后系统将自动重启，在此期间，请切勿进行关闭电源，硬盘拔插等操作，以免造成故障。</span>
            <span v-else>The system is being upgraded. During the upgrade, all functions will be unavailable. This process is expected to take 20 minutes to several hours, depending on the complexity of the system. The system will restart automatically after the upgrade is completed. During this period, please do not turn off the power supply, unplug the hard disk, or other operations to avoid failures.</span>
          </div>
          <div v-if="isUpdateOk">
            <div class="configIngImg wait-icon-box">
              <!-- <i class="icon-64 wait-tip-icon icon icon-inservice64f"></i> -->
              <Iconfont class="icon-64 wait-tip-icon icon " type="icon-inservice64f"></Iconfont>
            </div>
            <p class="wait-tip">
              {{$store.state.language=='zh' ? '正在升级，请勿关闭' : 'Upgrading, please do not close'}}
            </p>
          </div>
          <div v-else>
            <div class="configIngImg">
              <!-- <i class="icon-64 error-tip-icon icon icon-error64f"></i> -->
              <Iconfont class="icon-64 error-tip-icon icon" type="icon-error64f"></Iconfont>
            </div>
            <p class="error-tip">
              {{$store.state.language=='zh' ? '升级失败' : 'Upgrade failed'}}
            </p>
          </div>
        </div>
      </div>
      <template slot="footer" v-if="current!=3">
        <!-- 上一步 -->
        <a-button v-if="current > 0" class="prev-btn" @click="handlePrev" :disabled="isDisabledPrev">{{$t('Prev')}}</a-button>
        <!-- 取消 -->
        <a-button key="back" @click="handleCancel">{{$t('Cancel')}}</a-button>
        <!-- 下一步 -->
        <a-button 
          key="submit"
          v-if="current < steps.length - 1"
          type="primary"
          :disabled="isDisabledNext"
          @click="handleNext"
        >
          {{current==2 ? $t('Sure') : $t('Next')}}
        </a-button>
      </template>
      <template slot="footer" v-else>
        <!-- <a-button disabled style="visibility:hidden;" type="primary">{{$t('Finished')}}</a-button> -->
        <!-- 关闭 -->
        <a-button :disabled="isUpdateOk" type="primary" @click="handleCancel">{{$t('Close')}}</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import request from '@/request/request'
import PacketOperationTip from '@/components/copyright/updateSystem/PacketOperationTip'

export default {
  name: "UpdateSystem",
  props: ['visible', 'currentVersion',],
  components: { PacketOperationTip },
  data() {
    return {
      update_dialog: false,
      current: 0,
      steps: [
        {
          ch_title: '步骤一',
          en_title: 'Step 1',
          ch_tip: '风险告知',
          en_tip: 'Risk notification',
        },
        {
          ch_title: '步骤二',
          en_title: 'Step 2',
          ch_tip: '导入升级包',
          en_tip: 'Import upgrade package',
        },
        {
          ch_title: '步骤三',
          en_title: 'Step 3',
          ch_tip: '升级检测',
          en_tip: 'Upgrade detection',
        },
        {
          ch_title: '步骤四',
          en_title: 'Step 4',
          ch_tip: '升级中',
          en_tip: 'Upgrading',
        },
      ],
      confirmInputValue: '',//我已知晓全部风险，仍要升级
      isDisabledNext: true,
      fileList: [],
      isDisabledPrev: false,
      versionTips: [
        {
          ch_title: '当前系统版本号：', en_title: 'Current system version:', value: 'PentaStor '+this.currentVersion,
        },
        {
          ch_title: '升级包版本号：', en_title: 'Upgrade package version:', value: '-',
        }
      ],
      packetStatus: 0,
      uploadLoading: false,
      isUpdateOk: true,
      isUploadSuccess: false,
      backendIp: 'http://192.168.5.61:8000/'
    }
  },

  mounted() {
    this.update_dialog = this.visible;
  },

  beforeDestroy() {
    this.update_dialog = false;
  },

  watch: {
    confirmInputValue(newValue) {
      if(this.$store.state.language == 'zh' && newValue == '我已知晓全部风险，仍要升级') {
        this.isDisabledNext = false;
      }else if(this.$store.state.language == 'en' && newValue == 'I know all the risks and still need to upgrade') {
        this.isDisabledNext = false;
      }else {
        this.isDisabledNext = true;
      }
    },
    fileList(newValue) {
      if(newValue.length == 0) {
        this.isDisabledNext = true;
      }else {
        // // this.isDisabledNext = false;
      }
    }
  },

  methods: {
    //下一步
    handleNext() {
      this.current++;
      //导入升级包
      if(this.current == 1) {
        if(this.fileList.length != 0 && this.isUploadSuccess) {
          this.isDisabledNext = false;
        }else {
          //导入升级包
      if(this.current == 1) {
        if(this.fileList.length != 0 && this.isUploadSuccess) {
          this.isDisabledNext = false;
        }else {
          this.isDisabledNext = true;
        }
      }
        }
      }
      //检测升级包
      if(this.current == 2) {
        this.handleUpload();
        this.isDisabledPrev = true;
      }else {
        this.isDisabledPrev = false;
      }
      if(this.current == 3) {
        this.updateSystem();
      }
    },

    //上一步
    handlePrev() {
      this.isDisabledNext = false;
      this.current--;
    },

    //删除上传文件
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      this.fileList = [file];//上传一个
      // this.fileList = [...this.fileList, file];//上传多个
      this.handleUploadPacket();
      return false; 
    },

    //上传升级包
    handleUploadPacket() {
      this.uploadLoading = true;
      this.isDisabledNext = true;
      this.isDisabledPrev = true;
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('file', file);
        // console.log('上传的文件', formData.get('file'))
      });
      this.$axios({
        method: 'post',
        url: this.allurl + 'version/upload_file',
        headers: {
          'Content-Type': 'multipart/form-data',
          "authorization": 'Bearer ' + JSON.parse(localStorage.getItem('authToken')), 
        },
        data: formData
      }).then(res => {
        // console.log('上传升级包', res)
        if(res.data.code == 0) {
          this.isUploadSuccess = true; //是否上传成功
          this.isDisabledNext = false;
          this.isDisabledPrev = false;
          this.$message.success(this.$t('Upload-ok'));
        }else {
          this.isUploadSuccess = false;
          this.$message.error(res.data.msg);
        }
      }).catch(err => {

      }).finally(() => {
        this.uploadLoading = false;
      }).finally(() => {
        this.uploadLoading = false;
      })
    },

    //检测升级包
    handleUpload() {
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('file', file);
      });
      request('get', 'version/check_upgrade').then(res => {
        // console.log('检测文件包', res)
        this.isDisabledPrev = false;
        if(res.data.code == 0) {//文件正常
          this.packetStatus = 4;
          this.versionTips[1].value = res.data.value;//升级的版本
          this.isDisabledNext = false;
        }else if(res.data.code == 10000 || res.data.code == 10002) {//文件错误
          this.packetStatus = 3;
          this.isDisabledNext = true;
        }else if(res.data.code == 10004){//当前版本包比当前系统版本低
          this.packetStatus = 1;
          this.isDisabledNext = true;
        }else if(res.data.code == 10005){//当前版本已是最新，即版本包与当前系统版本相等
          this.packetStatus = 2;
          this.isDisabledNext = true;
        }else if(res.data.code == 10003 || res.data.code == -999) {//服务异常
          this.packetStatus = 5;
          this.isDisabledNext = true;
        }
      });
    },

    //开始更新系统
    updateSystem() {
      request('get', 'version/upgrade').then(res => {
        if(res.data.code == 0) {
          this.$message.success('系统更新完成，请重新登录！');
          this.$router.push('/');
        }else if(res.data.code == -999) {//服务异常
          this.isUpdateOk = false;
          this.$message.error('服务异常！');
        }else {
          this.isUpdateOk = false;
          this.$message.error('系统更新失败！');
        }
      }).catch(() => {
        this.$message.success('系统更新完成，请重新登录！');
        this.$router.push('/');
      })
    },

    //关闭升级弹窗
    handleCancel() {
      this.$emit('closeUpdateDialog', false)
    },
  },
}
</script>
<style scoped>
  .top-tip {
    padding: 10px;
    background-color: rgba(7, 133, 253, 0.1);
    border-radius: 4px;
    border: solid 1px var(--themeColor);
    margin-bottom: 15px;
  }
  .top-tip img {
    margin-right: 5px;
    vertical-align: text-bottom;
  }
  .prev-btn {
    float: left;
    border-color: var(--themeColor);
    color: var(--themeColor);
  }
  .prev-btn:hover {
    color: #40a9ff;
    border-color: #40a9ff;
  }
  .prev-btn[disabled] {
    background-color: #f5f5f5;
    border-color: #d9d9d9;
    color: rgba(0, 0, 0, 0.25);
  }
  .steps-content {
    margin: 15px 0;
  }
  .warn-tip {
    color: var(--mainRedColor);
    background-color: #fae8ec;
    border-left: 2px solid var(--mainRedColor);
    padding: 6px 8px;
    user-select: none;
    margin-bottom: 15px;
  }
  .font-weight-color {
    font-weight: 700;
    color: var(--themeColor);
  }
  .version-div {
    margin: 20px 0;
  }
  .version-div > .ant-row:nth-of-type(1) .version-tip-label,
  .version-div > .ant-row:nth-of-type(1) .version-tip-value {
    border-bottom: none;
  }
  .version-div > .ant-row .version-tip-value {
    border-left: none;
  }
  .version-tip-label,
  .version-tip-value {
    /* width: 100%; */
    padding: 9px;
    box-sizing: border-box;
    text-align: right;
    border: 1px solid #b2b2b2;
    background-color: #f2f2f2;
  }
  .version-tip-value {
    text-align: left;
    background-color: #fff;
  }
  .error-color {
    color: var(--mainRedColor);
  }
  .ok-color {
    color: var(--mainGreenColor);
  }
  .tip-icon {
    color: var(--themeColor);
    margin-right: 5px;
  }

  .configIngImg {
    text-align: center;
    /* margin: 15px 0; */
  }
  .wait-icon-box {
    animation:iconRotate 2s linear infinite;
    -webkit-animation: iconRotate 2s linear infinite;
    -moz-animation: iconRotate 2s linear infinite;
    -o-animation: iconRotate 2s linear infinite;
  }
  @keyframes iconRotate{
    from {transform: rotate(0deg);}
    to {transform: rotate(360deg);}
  }
  .wait-tip-icon {
    color: var(--themeColor);
  }
  .error-tip-icon {
    color: var(--mainRedColor);
  }
  .icon-64 {
    font-size: 64px;
  }
  .error-tip {
    text-align: center;
  }
  .wait-tip {
    /* margin: 10px 0; */
    text-align: center;
  }
  .wait-tip:after {
    content: "";
    animation: dotRunning 2s infinite;
    -webkit-animation: dotRunning 2s infinite;
  }
  @keyframes dotRunning {
    0%,100% {
      content: "";
    }
    25% {
      content: ".";
    }
    50% {
      content: "..";
    }
    75% {
      content: "...";
    }
  }
  
  /* 步骤条样式 */
  ::v-deep.ant-steps-dot .ant-steps-item-tail {
    margin: 0 0 0 55px;
  }
  ::v-deep.ant-steps-dot .ant-steps-item-content {
    width: 115px;
  }
  ::v-deep.ant-steps-dot .ant-steps-item-icon {
    margin-left: 50px;
  }
  /* 步骤条样式end */
  ::v-deep.ant-modal-body {
    min-height: 382px;
  }
</style>